import 'package:async/async.dart';

import '../common/test_page.dart';

class AsyncMemoizerTestPage extends TestPage {

  late AsyncMemoizer cache;
  setUp() => cache = AsyncMemoizer();

  AsyncMemoizerTestPage(super.title) {
    test('AsyncMemoizer().runOnce()仅在第一次调用runOnce()时运行函数', () async {
      setUp();
      var count = 0;
      expect(await cache.runOnce(() => count++));
      expect(count);

      expect(await cache.runOnce(() => count++));
      expect(count);
    });

    test('AsyncMemoizer().future, AsyncMemoizer().runOnce()转发函数的返回值', () async {
      setUp();
      expect(cache.future);
      expect(cache.runOnce(() => 'value'));
      expect(cache.runOnce(() {}));
    });

    test('AsyncMemoizer().future, AsyncMemoizer().runOnce()转发异步函数的返回值', () async {
      setUp();
      expect(cache.future);
      expect(cache.runOnce(() async => 'value'));
      expect(cache.runOnce(() {}));
    });

    test('AsyncMemoizer().future, AsyncMemoizer().runOnce()转发来自异步函数的错误', () async {
      expect(cache.future);
      expect(cache.runOnce(() async => throw 'error'));
      expect(cache.runOnce(() {}));
    });

  }

}